package com.simen.connectandroid.command;

import com.simen.connectandroid.command.utils.CommandCreator;
import com.simen.connectandroid.model.Device;
import com.simen.hellobytes.StringUtil;
import com.simen.hellobytes.runtime.RuntimeHelper;

/**
 * 获取指定包名的apk文件路径
 * Created on 2021/11/18 13:00.
 *
 * @author Simen
 */
public class GetPackagePathCommand extends AdbCommand<GetPackagePathCommand> {

    private boolean commandResult;

    private String packageName;
    private String packagePath;

    public GetPackagePathCommand(String packageName) {
        this.packageName = packageName;
    }

    public GetPackagePathCommand(Device device, String packageName) {
        super(device);
        this.packageName = packageName;
    }

    @Override
    public GetPackagePathCommand exec() {
        if (StringUtil.isTrimEmpty(packageName)) {
            System.out.println("packageName can't be empty");
            return this;
        }

        RuntimeHelper runtimeHelper = RuntimeHelper.create(CommandCreator.createAdb()
                .appendAdbDevice(device)
                .appendParam("shell pm path " + packageName)
                .build());
        runtimeHelper.exec();

        commandResult = runtimeHelper.getProcessCode() == 0;
        log = runtimeHelper.getOutputLog();

        if (execResult()) {
            packagePath = log.substring(8);
        }

        return this;
    }

    @Override
    public boolean execResult() {
        return commandResult && log.startsWith("package:");
    }

    public String getPackagePath() {
        return packagePath;
    }
}
